package microarray;

import java.io.*;
import java.net.URLConnection;
import java.util.HashMap;

public class Sample extends MicroArrayElement
{
	private Platform platform;

	public boolean isControl()
	{
		return platform.isControl(id);
	}

	private HashMap<String, Double> geneMap;

	public Sample(String id, Platform p) throws IOException
	{
		super(id);
		this.platform = p;
		parent = platform.parent;
		build();
	}

	public String getDir()
	{
		return (platform.getDir());
	}

	public void scrapeAndRecord() throws IOException
	{
		if (parent.overwriteWhenFileExists()
				|| !(new File(getDir() + id + "_map.txt").exists()))
		{
			new SampleDownloader().doDownload(id, 5000, 10);

			record();
		}
	}

	public void record() throws IOException
	{
		new File(getDir()).mkdirs();
		File map = new File(getDir() + id + "_map.txt");

		printDebug("writing to " + map);
		FileOutputStream out = new FileOutputStream(map);
		PrintStream p = new PrintStream(out);
		for (String geneID : geneMap.keySet())
		{
			p.println(geneID + "\t" + geneMap.get(geneID));
		}
		p.close();
	}

	public void build()
	{

	}

	public class SampleDownloader extends Downloader
	{
		public void download() throws IOException
		{
			printDebug("scraping specifics " + id + ": "
					+ getDataURL().getQuery());
			URLConnection c = getDataURL().openConnection();
			BufferedReader r = new BufferedReader(new InputStreamReader(c
					.getInputStream()));
			String line = r.readLine();
			boolean inTable = false;
			int valuePosition = 1;
			while (line != null && !inTable)
			{
				inTable = line.contains("!sample_table_begin");
				line = r.readLine();
			}
			if (inTable)
			{ // find valuePosition from the header.
				line = r.readLine();
				String[] header = line.split("\t");
				for (int i = 0; i < header.length; i++)
				{
					if (header[i].equals("VALUE"))
						valuePosition = i;
				}
			}

			geneMap = new HashMap<String, Double>();
			String gene;
			String geneID;
			String activationString;
			double activation;
			while (line != null && inTable)
			{
				inTable = !line.contains("!sample_table_end");
				if (inTable)
				{
					String[] row = line.split("\t");
					geneID = row[0].toUpperCase();
					gene = platform.getGene(geneID);
					if (gene != null)
					{
						if (row.length <= valuePosition)
						{
							// System.out.println("Incomplete line: " + line);
						} else
						{
							activationString = row[valuePosition];
							try
							{
								activation = Double
										.parseDouble(activationString);
								geneMap.put(gene, activation);
							} catch (NumberFormatException e)
							{
								geneMap.put(gene, null);
							}
						}
					} else
						System.out.println("No such gene in map: " + geneID);

					line = r.readLine();
				}
			}
		}
	}
}